<template>
  <div class="group-list-container">
    <el-input v-model="searchText" placeholder="请输入分组名" clearable :prefix-icon="Search" class="group-search" />

    <el-popover :visible="popoverVisible" placement="right" title="添加分组" :width="200" trigger="click">
      <template #reference>
        <el-button type="primary" :icon="Plus" class="add-button" @click="handleAddGroup">
          添加分组
        </el-button>
      </template>
      <template #default>
        <el-input v-model="groupName" placeholder="请输入分组名称" maxlength="10" show-word-limit></el-input>
        <div style="margin-top: 10px; text-align: right">
          <el-button size="small" @click="popoverVisible = false">取消</el-button>
          <el-button size="small" type="primary" @click="handleAdd">确定</el-button>
        </div>
      </template>
    </el-popover>

    <div class="group-list">
      <div v-for="(group, index) in filteredGroups" :key="index"
        :class="['group-item', { active: (activeGroup === group.id) || (activeGroup === '-1' && index === 0) }]"
        @click="handleClick(group)" @mouseenter="hoverIndex = index" @mouseleave="hoverIndex = -1">
        <div class="name">
          <img v-if="fileType !== 1" :src="defaultFolder" class="material-icon" />
          <img v-else :src="videoFolder" class="material-icon" />
          <span>{{ group.name }}</span>
        </div>
        <div class="count" v-show="hoverIndex !== index">{{ group.count }}</div>
        <div class="opera" v-show="hoverIndex === index">
          <el-popover :visible="editVisibleId === group.id" placement="right" :width="200" trigger="click">
            <template #reference>
              <i class="iconfont-sys edit-icon" @click.stop="handleEdit(group)">&#xe65f;</i>
            </template>
            <template #default>
              <el-input v-model="editGroupName" placeholder="请输入分组名称" maxlength="10" show-word-limit></el-input>
              <div style="margin-top: 10px; text-align: right">
                <el-button size="small" @click="editVisibleId = null">取消</el-button>
                <el-button size="small" type="primary" @click="editGroup(group)">确定</el-button>
              </div>
            </template>
          </el-popover>
          <i class="iconfont-sys del-icon" @click.stop="deleteGroup(group)">&#xe783;</i>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import {
  getArticleGroup,
  addArticleGroup,
  delArticleGroup,
  editArticleGroup
} from '@/api/materialManagement'
import defaultFolder from '@/assets/img/folder.png'
import videoFolder from '@/assets/img/video-folder.png'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  fileType: {
    type: Number
  }
})


const emit = defineEmits(['selectGroup', 'get-groupId'])

interface GroupItem {
  id: string
  name: string
  count: number
}

const searchText = ref('')
const activeGroup = ref('-1')
const hoverIndex = ref(-1)
const popoverVisible = ref(false)
const groupName = ref('')
const editVisibleId = ref<string | null>(null)
const editGroupName = ref('')

const groups = ref<GroupItem[]>([])

const filteredGroups = computed(() => {
  if (!searchText.value) return groups.value
  return groups.value.filter((group) => group.name.includes(searchText.value))
})

function handleClick(group: GroupItem) {
  console.log(group, "group===");

  activeGroup.value = group.id
  emit('selectGroup', group)
}

function handleEdit(group: GroupItem) {
  editVisibleId.value = group.id
  editGroupName.value = group.name
}

async function editGroup(group: GroupItem) {
  const res = await editArticleGroup(group.id, {
    name: editGroupName.value,
  })
  if (res.code === '00000') {
    ElMessage.success('更新成功')
    editVisibleId.value = null
    await getData()
  }
}


async function handleDelete(ids: any) {
  const res = await delArticleGroup(ids)
  if (res.code === '00000') {
    await getData()
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.msg)
  }
}

const deleteGroup = (group: GroupItem) => {
  ElMessageBox.confirm('确定要删除这个分组吗？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    handleDelete(group.id)
  })
}

async function handleAdd() {
  try {
    if (groupName.value === '') {
      ElMessage.warning('请输入分组名称')
      return
    }

    const res = await addArticleGroup({
      name: groupName.value
    })
    if (res.code === '00000') {
      ElMessage.success('新增成功')
      await getData()
    }
  } catch (e) {
  } finally {
    popoverVisible.value = false
  }
}

function handleAddGroup() {
  popoverVisible.value = true
  groupName.value = ''
}
const groupId = ref('')


async function getData() {
  const res = await getArticleGroup()
  if (res.code === '00000') {
    const previousActiveId = activeGroup.value
    const isFirstLoad = previousActiveId === '-1'
    groups.value = res.data
    const existsActive = groups.value.find((g: any) => g.id === previousActiveId)
    if (isFirstLoad || !existsActive) {
      const firstId = groups.value[0]?.id
      if (firstId) {
        activeGroup.value = firstId
        emit('get-groupId', firstId)
      }
    }
  }
}

const getDefaultGroupId = () => {
  let index = groups.value.findIndex((e: any) => e.groupName === '默认分组')
  console.log(index, "index===");

  if (index !== -1) {
    return groups.value[index].id
  }
}

defineExpose({
  getData,
  getDefaultGroupId
})

onMounted(() => {
  getData()
})
</script>

<style scoped lang="scss">
.group-list-container {
  width: 220px;
  padding: 12px;
  border-right: 1px solid #eee;
  position: relative;
  background: #fff;
}

.group-search {
  width: 100%;
  margin-bottom: 10px;
}

.add-button {
  width: 100%;
  margin-bottom: 16px;
}

.group-list {
  border-top: 1px solid #f0f0f0;
}

.group-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 10px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.2s;

  .name {
    display: flex;
    align-items: center;

    .material-icon {
      width: 18px;
      height: 18px;
      margin-right: 5px;
    }
  }
}

.group-item:hover {
  background-color: #eff8ec;

  .count {
    display: none;
  }

  .opera {
    display: block;
  }
}

.group-item.active {
  color: var(--el-color-primary);
  background-color: #eff8ec;
  border-right: 2px solid var(--el-color-primary);
}

.group-item .count {
  color: #999;
  font-size: 13px;
}

.opera {
  display: none;

  .edit-icon {
    color: var(--el-color-primary);
    margin-right: 6px;
  }

  .del-icon {
    color: #f34965;
  }
}
</style>
